package com.bwie.gateway;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * TODO
 *
 * @Description
 * @Author 36167
 * @Date 2025/3/6 9:44
 **/


@Component
public class GateWayConfig implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String ip = request.getRemoteAddress().toString();
        String url = request.getURI().getPath();

        if (a1(url)){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        if (token==null){
            System.out.println("token不存在");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String s = body.get("username", String.class);
        String redistoken = stringRedisTemplate.opsForValue().get(s);
        if (redistoken==null){
            System.out.println("token过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if (!token.equals(redistoken)){
            System.out.println("token错误");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);

    }

    private boolean a1(String url) {
        ArrayList<String> list = new ArrayList<>();
        list.add("/gall/list");
        list.add("/user/login");
        if (ref(url,list)){
            return true;
        }else {
            return false;
        }
    }

    private boolean ref(String url, ArrayList<String> list) {
        AtomicBoolean a= new AtomicBoolean(false);
        list.stream().filter(x->url.contains(x)).forEach(b->{
            a.set(true);
        });
        return a.get();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
